//
//  ImageGridTableViewController.m
//  ImageGridCell
//
//  Created by 为为 on 14-7-25.
//  Copyright (c) 2014年 为为. All rights reserved.
//

#import "ImageGridTableViewController.h"
#import "CImageGridCell.h"
#import "DBOperation.h"
#import "DBUtil.h"
#import "SDWebImageManager.h"
#import "NetworkAPI.h"
#import "NetworkOperation.h"
#import "Util.h"
#import "MJRefresh.h"

@interface ImageGridTableViewController ()
{
	NSMutableArray* itemArray;
}

@end

@implementation ImageGridTableViewController

- (id)initWithArray:(NSArray *)array
{
	self = [super init];
	if (self) {
		if ([array isKindOfClass:[NSMutableArray class]]) {
			itemArray = (NSMutableArray*)array;
		} else {
			itemArray = [NSMutableArray arrayWithArray:array];
		}
	}
	return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.mtableView registerClass:[NImageGridCell class] forCellReuseIdentifier:@"cell"];
    
    [self setupRefresh];
	
	[self initNavigationItem];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - navigation

- (void)initNavigationItem {
	UIImage* image = [UIImage imageNamed:@"close_button.png"];
    CGFloat imageWidth = 22;
	if (image.size.width > imageWidth) {
		image = [CImageUtil imageFromImage:image scaleToSize:CGSizeMake(imageWidth, imageWidth)];
	}
	self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(cancelButtonPressed:)];
    
    
    if (!self.hideRightBarButtonItem) { 
        image = [UIImage imageNamed:@"reset_button.png"];
        imageWidth = 25;
        if (image.size.width > imageWidth) {
            image = [CImageUtil imageFromImage:image scaleToSize:CGSizeMake(imageWidth, imageWidth)];
        }
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(resetButtonPressed:)];
    }
}

#pragma mark method

- (void)cell:(NImageGridCell*)cell deleteImage:(UIImage*)image atIndex:(NSUInteger)index
{
    NSIndexPath* indexPath = [self.mtableView indexPathForCell:cell];
	
	if (self.imageDeletedBlock) {
		self.imageDeletedBlock(self, indexPath.section, [self imageIndexForIndexPath:indexPath index:index], image);
	}
}

- (void)cell:(NImageGridCell*)cell selectImage:(UIImage*)image atIndex:(NSUInteger)index
{
    if (self.imagePressedBlock) {
        NSIndexPath* indexPath = [self.mtableView indexPathForCell:cell];
        self.imagePressedBlock(self, indexPath.section, [self imageIndexForIndexPath:indexPath index:index], image);
    }
}

- (void)cellBeginDelete:(NImageGridCell*)cell atIndexPath:(NSIndexPath*)indexPath
{
	NSArray* cellsInSameSection = [self cellsInSectionWithIndexPath:indexPath];
	for (NImageGridCell* theCell in cellsInSameSection) {
		theCell.deleting = YES;
	}
}

- (void)cellEndDelete:(NImageGridCell*)cell atIndexPath:(NSIndexPath*)indexPath
{
	NSArray* cellsInSameSection = [self cellsInSectionWithIndexPath:indexPath];
	for (NImageGridCell* theCell in cellsInSameSection) {
		theCell.deleting = NO;
	}
}

- (NSArray*)cellsInSectionWithIndexPath:(NSIndexPath*)indexPath
{
	NSArray* visibleCells = [self.mtableView visibleCells];
	NSMutableArray* cells = [NSMutableArray array];
	
	for (NImageGridCell* theCell in visibleCells) {
		NSIndexPath* theIndexPath = [self.mtableView indexPathForCell:theCell];
		if (indexPath.section == theIndexPath.section) {
			[cells addObject:theCell];
		}
	}
	
	return cells;
}

#pragma mark refersh

- (void)setupRefresh
{
    self.mtableView.mj_footer = [MJRefreshFooter footerWithRefreshingBlock:^{
        [NetworkOperation getNewGroups:^(bool succeed) {
            [self.mtableView reloadData];
            [self.mtableView.mj_footer endRefreshing];
        }];
    }];
#pragma TODO
//    self.mtableView.footerPullToRefreshText = nil;
//    self.mtableView.footerReleaseToRefreshText = nil;
//    self.mtableView.footerRefreshingText = nil;
    
}

#pragma mark action

- (IBAction)cancelButtonPressed:(id)sender {
	if (self.cancelPressedBlock) {
		self.cancelPressedBlock(self);
	}
}

- (IBAction)resetButtonPressed:(id)sender {
	if (self.resetPressedBlock) {
		self.resetPressedBlock(self);
	}
}

#pragma mark data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return itemArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableDictionary* entry = [itemArray objectAtIndex:section];
    int grpid = [[entry objectForKey:GROUP_KEY_ID] intValue];
	int imageCount = [DBOperation imageCountForGroupID:grpid];
    NSUInteger imagePreRow = [NImageGridCell imagesPerRow];
    
	return (imageCount+imagePreRow-1)/imagePreRow;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSMutableDictionary* entry = [itemArray objectAtIndex:section];
    NSString* title = [entry objectForKey:GROUP_KEY_TITLE];
    return title;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NImageGridCell* cell = [self.mtableView dequeueReusableCellWithIdentifier:@"cell"];
    [self provideDateForCell:cell atIndexPath:indexPath];
    cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
	
	return cell;
}

- (void)provideDateForCell:(NImageGridCell*)cell atIndexPath:(NSIndexPath*)indexPath
{
	NSMutableDictionary* entry = [itemArray objectAtIndex:indexPath.section];
    [self fillCell:cell withEntryData:entry atIndexPath:indexPath];
}

- (void)fillCell:(NImageGridCell*)cell withEntryData:(NSMutableDictionary*)entry atIndexPath:(NSIndexPath*)indexPath
{
	if (entry && cell) {
		NSArray* imageArray = [DBOperation imageArrayForImageGridTableViewController:self
																	   imageGridCell:cell
																		 atIndexPath:indexPath
																	   withGroupDict:entry];
        cell.imageArray = imageArray;
        cell.deletable = [[entry objectForKey:GROUP_KEY_DELETE] boolValue];
		
		NSNumber* deleting = [entry objectForKey:@"deleting"];
		cell.deleting = deleting?deleting.boolValue:NO;
		
        __weak typeof(self) bself = self;
		cell.imageDeletedBlock = ^(NImageGridCell* acell, UIImage* image, NSUInteger index) {
            [bself cell:acell deleteImage:image atIndex:index];
		};
		cell.imagePressedBlock = ^(NImageGridCell* acell, UIImage* image, NSUInteger index) {
			[bself cell:acell selectImage:image atIndex:index];
		};
		cell.imageBeginDeleteBlock = ^(NImageGridCell* acell) {
			[entry setObject:[NSNumber numberWithBool:YES] forKey:@"deleting"];
			[bself cellBeginDelete:acell atIndexPath:indexPath];
		};
		cell.imageEndDeleteBlock = ^(NImageGridCell* acell) {
			[entry setObject:[NSNumber numberWithBool:NO] forKey:@"deleting"];
			[bself cellEndDelete:acell atIndexPath:indexPath];
		};
	}
}

#pragma mark dalegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = [NImageGridCell height];
    
	return height;
}

- (NSRange)imageRangeForIndexPath:(NSIndexPath*)indexPath
{
    NSRange range;
    
    range.location = indexPath.row*[NImageGridCell imagesPerRow];
    range.length = [NImageGridCell imagesPerRow];
    
    return range;
}

- (NSUInteger)imageIndexForIndexPath:(NSIndexPath*)indexPath index:(NSUInteger)idx
{
    NSUInteger index = 0;
    
    index = indexPath.row*[NImageGridCell imagesPerRow]+idx;
    
    return index;
}

@end
